package com.qf.bookshop2.controller;

import com.qf.bookshop2.model.Book;
import com.qf.bookshop2.model.User;
import com.qf.bookshop2.service.IBuyBookService;
import com.qf.bookshop2.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
//@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    IBuyBookService buyBookService;

    @RequestMapping("/login.html")
    public String toLogin(){
        return "login";
    }


    @RequestMapping("/logic.html")
    public String toLogic(){
        return "logic";
    }

    @RequestMapping("/logic")
    public String logic(String username, String password){
        User user=new User();
        user.setUsername(username);
        user.setPassword(password);
        userService.logic(user);
        return "redirect:login.html";
    }

    @RequestMapping("/login")
    public String login(String username, String password, Model model, HttpSession session){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token=new UsernamePasswordToken(username,password);
        try{
            subject.login(token);
            System.out.println("登录成功");
            session.setAttribute("username",username);
            return "redirect:index";

        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码错误");
            System.out.println("密码错误");
        }catch (UnknownAccountException e){
            model.addAttribute("msg","用户名不存在");
            System.out.println("用户名不存在");
        }


        System.out.println(username+":"+password);
        return "fail";
    }

    @RequestMapping("/update")
    public String update(){
        System.out.println("可以删除了");
        return "update";
    }





    @RequestMapping("/index")
    public  String toIndex(Model model){
        List<Book> books= buyBookService.getAllBooks();
        model.addAttribute("books",books);
        return "index";

    }
}
